import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score

# 加载Excel文件数据
file_similarity = r"C:\Users\zlsjJSSA\Desktop\工作簿1.xlsx"
df_similarity = pd.read_excel(file_similarity, sheet_name='Sheet1')  # 假设最高相似度数据在第一个表单
df_true_label = pd.read_excel(file_similarity, sheet_name='Sheet2')  # 假设true_label数据在第二个表单

# 定义阈值范围
thresholds = np.arange(0.6, 0.91, 0.01)

# 初始化存储评估指标的列表
accuracy_scores = []
precision_scores = []
recall_scores = []
f1_scores = []

# 计算每个阈值下的评估指标
for threshold in thresholds:
    # 应用阈值进行预测
    predicted_labels = np.where(df_similarity["最高相似度"] >= threshold, 1, 0)

    # 计算评估指标
    accuracy = accuracy_score(df_true_label["true_label"], predicted_labels)
    precision = precision_score(df_true_label["true_label"], predicted_labels)
    recall = recall_score(df_true_label["true_label"], predicted_labels)
    f1 = f1_score(df_true_label["true_label"], predicted_labels)

    # 添加到列表中
    accuracy_scores.append(accuracy)
    precision_scores.append(precision)
    recall_scores.append(recall)
    f1_scores.append(f1)

# 绘制折线图
plt.figure(figsize=(10, 6))

# 绘制四个评估指标的折线
plt.plot(thresholds, accuracy_scores, label='Accuracy')
plt.plot(thresholds, precision_scores, label='Precision')
plt.plot(thresholds, recall_scores, label='Recall')
plt.plot(thresholds, f1_scores, label='F1 Score')

# 添加标题和标签
plt.title('Evaluation Metrics vs. Similarity Threshold')
plt.xlabel('Similarity Threshold')
plt.ylabel('Score')

# 添加图例和网格
plt.legend()
plt.grid(True)

# 调整布局使图像更美观
plt.tight_layout()

# 保存为图片
plt.savefig('evaluation_metrics.png')

# 显示图像
plt.show()
